package cn.sh.library.gmwx.utils;

import javax.servlet.http.HttpServletRequest;

public class FullLink {
	/**
	 * 获取客户端用户IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		// System.out.println("用户IP：" + ip);
		return ip;
	}

	public static boolean isInnerIP(String ip) {
		boolean bInnerIP = false;
		// 私有地址的范围:
		// 1.A类地址中:10.0.0.0 到10.255.255.255
		// 2.B类地址中:172.16.0.0 到172.31.255.255
		// 3.C类地址中:192.168.0.0 到192.168.255.255
		// 4.本机地址: 127.0.0.1

		String[] ips = SharpString(ip, ".");
		int[] ipaddress = new int[ips.length];
		for (int i = 0; i < ipaddress.length; i++) {
			ipaddress[i] = Integer.parseInt(ips[i]);
		}
		if (ipaddress[0] == 10)
			bInnerIP = true;
		if (ipaddress[0] == 172 && ipaddress[1] >= 16 && ipaddress[1] <= 31)
			bInnerIP = true;
		if (ipaddress[0] == 192 && ipaddress[1] == 168)
			bInnerIP = true;
		if (ip.equals("127.0.0.1"))
			bInnerIP = true;
		return bInnerIP;
	}

	private static String[] SharpString(String collec, String sharp) {
		int count = GetSubNum(collec, sharp);
		String[] ask_num = new String[count + 1];
		int i = 0;
		int pos = 0;
		i = 0;
		pos = collec.indexOf(sharp);
		if (pos == 0) {
			collec = collec.substring(1, collec.length());
			pos = collec.indexOf(sharp);
		}
		while (pos != -1) {
			ask_num[i] = GetSharpString(collec, sharp);
			i++;
			collec = CutSharpString(collec, sharp);
			pos = collec.indexOf(sharp);
		}
		if (i < ask_num.length)
			ask_num[i] = collec;
		return ask_num;
	}

	private static int GetSubNum(String st, String subst) {
		int pos = 0;
		int count = 0;
		String temp = st;
		if (temp.equals("")) {
			count = 0;
		} else {
			pos = temp.indexOf(subst);
			while (pos != -1) {
				if (pos != (temp.length() - 1))
					count++;
				temp = temp.substring(pos + 1, temp.length());
				pos = temp.indexOf(subst);
			}
			pos = st.indexOf(subst);
			if (pos == 0)
				count--;
		}
		return count;
	}

	private static String GetSharpString(String st, String sharp) {
		int pos = st.indexOf(sharp);
		String re = "";
		if (pos == -1)
			re = st;
		else
			re = st.substring(0, pos);
		return re;
	}
	
	private static String CutSharpString(String st, String sharp) {
		int pos = st.indexOf(sharp);
		String re = "";
		if (pos == -1)
			re = "";
		else
			re = st.substring(pos + 1, st.length());
		return re;
	}
}
